package smartKiwi;
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.Path;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import java.util.logging.Logger;







import javax.swing.JOptionPane;

import org.apache.commons.codec.binary.Base64;



import org.java_websocket.server.WebSocketServer;


//import vue.ConfirmationFrame;
import net.sf.jcarrierpigeon.WindowPosition;
import net.sf.jtelegraph.Telegraph;
import net.sf.jtelegraph.TelegraphType;

public class SmartKiwi implements Runnable {

	private Properties props;
	private static Logger logger = Logger.getLogger("SmartKiwiWindowsService");
	static private SmartKiwiServer server;

	public Properties getProps() {
		return props;
	}

	public void setProps(Properties props) {
		this.props = props;
	}

	public SmartKiwi(String _login, String _password, String _url, String _port) {
		props = new Properties();
		props.setProperty("login", _login);
		props.setProperty("password", _password);
		props.setProperty("URL", _url);
		props.setProperty("port", _port);
		logger.config("./resources/log4j.properties");
	}

	public SmartKiwi() {
		props = new Properties();

	}

	public void initSocketServer() {
		if (server != null) {
			try {
				server.stop();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		try {
			int port = Integer.parseInt(props.getProperty("port"));
			server = new SmartKiwiServer(port,this);
			Thread t = new Thread(this);
			t.start();
		} catch (IOException e) {

			e.printStackTrace();
		} catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	public void run() {
		try {
			while (true) {
				BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
				String line;
				StringBuilder out = new StringBuilder();
		        while ((line = in.readLine()) != null) {
		            out.append(line);
		            System.out.println(line);
		            if(line.isEmpty())
		            	break;
		        }
				traiterRequete(out.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void traiterRequete(String request) {
		int returnCode = -1;
		SmartKiwiRequest req = new SmartKiwiRequest(this.props);
		if (request.startsWith("SENDDOCUMENT")) {
			try {
				
				//Get value of forceFiche (false if not specified)
				String forceFiche = request.split(" ")[request.split(" ").length-1];
				String ficheId = "";
				String dossierId = "";
				String b64Content = "";
				String fileName = "";
				if(forceFiche.equals("true"))
				{
					//AFFICHE IHM FORCE FICHE
				}
				
				//Get content in B64 from file path
				String strPath = request.substring(request.indexOf("\"")+1, request.lastIndexOf("\""));
				Path path = Paths.get(strPath);
				byte[] data = Files.readAllBytes(path);
				b64Content = new Base64().encodeToString(data);
				fileName = path.toFile().getName();

				//BUILD THE JSON OBJECT
				String jsonObject = "{\"ficheId\":\""+ficheId+"\",\"dossierId\":\""+dossierId+"\",\"content\":\""+b64Content+"\",\"fileName\":\""+fileName+"\"}";
				JOptionPane.showMessageDialog(null, jsonObject);
				//req.envoyerDocument(jsonObject);
				if (returnCode == -1) { 
					Telegraph telegraph = new Telegraph("Request result",
							"Connection failed", TelegraphType.NOTIFICATION_ERROR,
							WindowPosition.BOTTOMRIGHT, 4000);
					telegraph.animate();
				} else if (returnCode == 0 || returnCode == 1) { 
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else if (request.startsWith("SENDTEXT")) {
			
			//Get value of forceFiche (false if not specified)
			String forceFiche = request.split(" ")[request.split(" ").length-1];
			String ficheId = "";
			String dossierId = "";
			String content = "";
			if(forceFiche.equals("true"))
			{
				//AFFICHE IHM FORCE FICHE
			}
			
			//Get content in B64 from file path
			content = request.substring(request.indexOf("\""), request.lastIndexOf("\""));

			//BUILD THE JSON OBJECT
			String jsonObject = "{\"ficheId\":\""+ficheId+"\",\"dossierId\":\""+dossierId+"\",\"content\":\""+content+"\"}";
			JOptionPane.showMessageDialog(null, jsonObject);
			//req.envoyerTexte(jsonObject);
			
			if (returnCode == -1) { 
				Telegraph telegraph = new Telegraph("Request result",
						"Connection failed", TelegraphType.NOTIFICATION_ERROR,
						WindowPosition.BOTTOMRIGHT, 4000);
				telegraph.animate();
			} else if (returnCode == 0 || returnCode == 1) { 
				
			}
		} else {
			Telegraph telegraph = new Telegraph("Request result",
					"Unknown Request", TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
		}
	}

	public int saveConfiguration() {
		File f = null;
		if (props == null)
			return -1;
		try {
			String str = System.getenv("SMART_KIWI_WINDOWS");
			String[] aPath = str.split(";");
			boolean exists=false;
			for(String path : aPath)
			{
				f = new File(path+"\\config.properties");
				JOptionPane.showMessageDialog(null, f.getAbsolutePath());
				if(f.exists())
				{
					exists = true;	
					break;
				}
			}
			if(exists)
			{
				OutputStream out = new FileOutputStream(f);
				props.store(out, "Configuration file for SmartKiwi plugin");
				logger.info("CONFIGURATION FILE PATH : " + f.getAbsolutePath());
				if(server== null || (server.getPort() != Integer.parseInt(props.getProperty("port"))))
					initSocketServer();
				return 0;
			}
			else
			{
				Telegraph telegraph = new Telegraph("Configuration save",
						"Could not find configuration file.",
						TelegraphType.NOTIFICATION_ERROR,
						WindowPosition.BOTTOMRIGHT, 4000);
				telegraph.animate();
				logger.severe("Could not find configuration file.");
			}
		} catch (IOException e) {
			e.printStackTrace();
			Telegraph telegraph = new Telegraph("Configuration save",
					"Could not save configuration file.",
					TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
			logger.severe("Could not save configuration file."
					+ f.getAbsolutePath());
		}
		return -1;
	}

	public int connection() {
		logger.info("TRYING TO CONNECT TO SMARTKIWI");
		logger.info("LOGIN :" + props.getProperty("login"));
		logger.info("PASSWORD :" + props.getProperty("password"));
		logger.info("URL :" + props.getProperty("URL"));
		if (props.getProperty("login").equals("")
				|| props.getProperty("password").equals("")
				|| props.getProperty("URL").equals("")) {
			logger.warning("LOGIN FAILED => LOGIN OR PASSWORD OR URL");
			Telegraph telegraph = new Telegraph("Connection status",
					"Cannot connect to the server.",
					TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
			return 2;
		}
		Telegraph telegraph = new Telegraph("Connection status",
				"Connected to the server.", TelegraphType.NOTIFICATION_DONE,
				WindowPosition.BOTTOMRIGHT, 4000);
		telegraph.animate();
		return 0;
	}

	public int loadConfiguration() {
		File f = null;
		if (props == null)
			props = new Properties();
		InputStream inp;
		try {
			String str = System.getenv("SMART_KIWI_WINDOWS");
			String[] aPath = str.split(";");
			boolean exists=false;
			for(String path : aPath)
			{
				f = new File(path+"\\config.properties");
				if(f.exists())
				{
					exists = true;	
					break;
				}
			}
			if(exists)
			{
				inp = new FileInputStream(f);
				props.load(inp);
				Telegraph telegraph = new Telegraph("Configuration load",
						"Configuration loaded sucessfully",
						TelegraphType.NOTIFICATION_DONE,
						WindowPosition.BOTTOMRIGHT, 4000);
				telegraph.animate();
				return 0;
			}
		} catch (FileNotFoundException e) {
			Telegraph telegraph = new Telegraph("Configuration load",
					"Configuration file not found.",
					TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
			logger.severe("Configuration file not found");
		} catch (IOException e) {
			Telegraph telegraph = new Telegraph("Configuration load",
					"Could not load configuration file.",
					TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
			logger.severe("Could not load configuration file");
		}
		return -1;
	}

	public Object setProperty(String key, String value) {
		if (props == null)
			return null;
		return props.setProperty(key, value);
	}

	public String getProperty(String key) {
		if (props == null)
			return null;
		return props.getProperty(key);
	}
}
